package com.siwei.mes.service.erp.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.StringHelperUtils;
import com.siwei.mes.entity.dto.PrintRwdextraExperimentInfo;
import com.siwei.mes.entity.dto.RwdextraUpdateLogDto;
import com.siwei.mes.entity.erp.*;
import com.siwei.mes.entity.mixproportion.MixProportion;
import com.siwei.mes.entity.mixproportion.MixProportionReport;
import com.siwei.mes.entity.mixproportion.MixProportionUpdateLog;
import com.siwei.mes.mapper.erp.RwdextraExtendUpdateLogMapper;
import com.siwei.mes.mapper.erp.RwdextraUpdateLogMapper;
import com.siwei.mes.mapper.mixProportion.MixProportionMapper;
import com.siwei.mes.mapper.mixProportion.MixProportionUpdateLogMapper;
import com.siwei.mes.service.erp.RwdextraService;
import com.siwei.mes.service.erp.RwdextraUpdateLogService;
import com.siwei.mes.service.experiment.PrintService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * ERP任务单修改记录(RwdextraUpdateLog)表服务实现类
 *
 * @author linzi
 * @since 2024-09-09 20:36:31
 */
@Slf4j
@Service
public class RwdextraUpdateLogServiceImpl implements RwdextraUpdateLogService {
    @Resource
    private RwdextraService rwdextraService;
    @Resource
    private RwdextraUpdateLogMapper rwdextraUpdateLogMapper;
    @Resource
    private MixProportionUpdateLogMapper mixProportionUpdateLogMapper;
    @Resource
    private RwdextraExtendUpdateLogMapper rwdextraExtendUpdateLogMapper;
    @Resource
    private MixProportionMapper mixProportionMapper;
    @Resource
    private PrintService printService;

    @Override
    public PageInfo<RwdextraUpdateLog> getPage(PageQuery<RwdextraUpdateLog, RwdextraUpdateLog> query) {
        RwdextraUpdateLog searchParam = query.getParams();
        searchParam.setFrwno(StringHelperUtils.trimString(searchParam.getFrwno()));
        PageInfo<RwdextraUpdateLog> pageInfo = PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> rwdextraUpdateLogMapper.getList(searchParam));
        List<RwdextraUpdateLog> list = pageInfo.getList();
        if (list.isEmpty()) {
            return pageInfo;
        }
        for (RwdextraUpdateLog rwdextraUpdateLog : list) {
            RwdextraInfo rwdextraInfo = JsonUtils.getObject(rwdextraUpdateLog.getExtrainfo(), RwdextraInfo.class);
            rwdextraUpdateLog.setFrwno(rwdextraInfo.getFRwno());
            rwdextraUpdateLog.setFjzbw(rwdextraInfo.getFJzbw());
            rwdextraUpdateLog.setFJhsl(rwdextraInfo.getFJhsl());
            rwdextraUpdateLog.setTpz(rwdextraInfo.getFTpz());
            rwdextraUpdateLog.setCustomerName(rwdextraInfo.getFHtdw());
            RwdextraExtend rwdextraExtend = JsonUtils.getObject(rwdextraUpdateLog.getRwdextraExtendBeforeJson(), RwdextraExtend.class);
            rwdextraUpdateLog.setProjectName(rwdextraExtend.getProjectName());
            if (rwdextraExtend.getSupplyStartTime() != null) {
                rwdextraUpdateLog.setSupplyTime(DateHelper.formatDateTime(rwdextraExtend.getSupplyStartTime(), "yyyy-MM-dd", Locale.CHINA) + (rwdextraExtend.getSupplyEndTime() == null ? "" : "-" + DateHelper.formatDateTime(rwdextraExtend.getSupplyEndTime(), "yyyy-MM-dd", Locale.CHINA)));
            }
            RwdextraExtend rwdextraExtendAfter = JsonUtils.getObject(rwdextraUpdateLog.getRwdextraExtendAfterJson(), RwdextraExtend.class);
            if (rwdextraExtendAfter == null) {
                continue;
            }
            /** 计划方量 **/
            if (StringUtils.isNotBlank(rwdextraExtendAfter.getPlanQuantity())) {
                rwdextraUpdateLog.setFJhsl(rwdextraExtendAfter.getPlanQuantity());
            }
            /** 施工部位 **/
            if (StringUtils.isNotBlank(rwdextraExtendAfter.getPlanQuantity())) {
                rwdextraUpdateLog.setFjzbw(rwdextraExtendAfter.getPouringPosition());
            }
            if (rwdextraExtendAfter.getSupplyStartTime() != null) {
                rwdextraUpdateLog.setSupplyTime(DateHelper.formatDateTime(rwdextraExtendAfter.getSupplyStartTime(), "yyyy-MM-dd", Locale.CHINA) + (rwdextraExtendAfter.getSupplyEndTime() == null ? "" : "-" + DateHelper.formatDateTime(rwdextraExtendAfter.getSupplyEndTime(), "yyyy-MM-dd", Locale.CHINA)));
            }

            rwdextraUpdateLog.setUpdateProjectName(rwdextraExtendAfter.getProjectName());
            if (rwdextraExtendAfter.getPrintJson() == null) {
                continue;
            }
            RwdextraPrintInfo rwdextraPrintInfo = JsonUtils.getObject(rwdextraExtendAfter.getPrintJson(), RwdextraPrintInfo.class);
            if (rwdextraPrintInfo == null) {
                continue;
            }

            if (rwdextraPrintInfo.getMixProportionInfo() != null) {
                rwdextraUpdateLog.setUpdatePhb(rwdextraPrintInfo.getMixProportionInfo().getProportionPhb());
            }

            RwdextraPrintInfo.Customer customer = rwdextraPrintInfo.getCustomer();
            if (customer != null) {
                /** 砼品种 **/
                if (StringUtils.isNotBlank(customer.getFtpz())) {
                    rwdextraUpdateLog.setTpz(customer.getFtpz());
                }
                /** 施工单位 **/
                if (StringUtils.isNotBlank(customer.getCustomerName())) {
                    rwdextraUpdateLog.setCustomerName(customer.getCustomerName());
                }
                /** 计划日期 **/
                if (StringUtils.isNotBlank(customer.getPlantimeStart())) {
                    rwdextraUpdateLog.setPlantime(customer.getPlantimeStart());
                }
                /** 供应数量 **/
                if (StringUtils.isNotBlank(rwdextraPrintInfo.getFWcsl())) {
                    rwdextraUpdateLog.setFhquantity(rwdextraPrintInfo.getFWcsl());
                }
                /** 完成方量 和供应数量是同一字段 为了使老的增补资料正常，所有保留之前的 **/
                if (StringUtils.isNotBlank(customer.getFhquantity())) {
                    rwdextraUpdateLog.setFhquantity(customer.getFhquantity());
                }
            }

        }
        return pageInfo;
    }

    @Override
    public RwdextraUpdateLog loadById(Long id) {
        return rwdextraUpdateLogMapper.loadById(id);
    }

    @Override
    public List<RwdextraUpdateLog> getAll(RwdextraUpdateLog entity) {
        return rwdextraUpdateLogMapper.getList(entity);
    }

    @Override
    public void insertLog(Integer fRwdh, String fPhbNo) {
        if (fRwdh == null) {
            log.info("新增任务单修改记录，任务单为空，不新增直接跳过");
            return;
        }
        Rwdextra rwdextra = rwdextraService.selectByFrwdh(fRwdh);
        if (rwdextra == null) {
            log.info("ERP任务单信息不存在，任务单号：【{}】", fRwdh);
            return;
        }
        RwdextraExtend rwdextraExtend = rwdextra.getRwdextraExtend();
        rwdextraExtend.setProjectName(rwdextra.getRwdextraInfo().getFGcmc());
        rwdextraExtend.setBuildName(rwdextra.getRwdextraInfo().getFHtdw());
        rwdextraExtend.setContractName(rwdextra.getContractName());
        /**如果配合比编号为空这里直接查询任务单最新的配合比*/
        if (StringUtils.isBlank(fPhbNo)) {
            if (StringUtils.isBlank(rwdextra.getPhbshow())) {
                log.info("配合比编号为空，任务单号：【{}】", fRwdh);
                fPhbNo = null;
            } else {
                fPhbNo = rwdextra.getPhbshow();
            }
        }

        RwdextraUpdateLog updateLogInfo = new RwdextraUpdateLog();
        updateLogInfo.setFrwdh(fRwdh);
        try {
            updateLogInfo.setCreater(StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : null);
        } catch (Exception e) {
            updateLogInfo.setCreater(null);
        }
        updateLogInfo.setCreateTime(new Date());
        /**这里查询最后一次任务单的修改记录  赋值到之前的数据*/
        RwdextraUpdateLog lastUpdateInfo = rwdextraUpdateLogMapper.selectByLastUpdateInfo(fRwdh);
        if (lastUpdateInfo != null) {
            updateLogInfo.setMixUpdateBeforeId(lastUpdateInfo.getMixUpdateAfterId());
            updateLogInfo.setMixUpdateBeforeJson(lastUpdateInfo.getMixUpdateAfterJson());
            updateLogInfo.setRwdextraExtendBeforeId(lastUpdateInfo.getRwdextraExtendAfterId());
            updateLogInfo.setRwdextraExtendBeforeJson(lastUpdateInfo.getRwdextraExtendAfterJson());
        } else {
            updateLogInfo.setMixUpdateBeforeId(null);
            updateLogInfo.setMixUpdateBeforeJson(new JSONObject());
            updateLogInfo.setRwdextraExtendBeforeId(null);
            updateLogInfo.setRwdextraExtendBeforeJson(new JSONObject());
        }

        if (StringUtils.isNotBlank(fPhbNo)) {
            /**这里获取最后一次配合比修改记录*/
            MixProportionUpdateLog mixProportionUpdateLog = mixProportionUpdateLogMapper.getLastUpdateLog(fPhbNo);
            if (mixProportionUpdateLog != null) {
                updateLogInfo.setMixUpdateAfterId(mixProportionUpdateLog.getId());
                updateLogInfo.setMixUpdateAfterJson(mixProportionUpdateLog.getAfterJson());
            } else {
                updateLogInfo.setMixUpdateAfterId(null);
                updateLogInfo.setMixUpdateAfterJson(new JSONObject());
            }
        } else {
            /**如果配合比编号没有传 这里修改前后都是一样的*/
            if (lastUpdateInfo != null) {
                updateLogInfo.setMixUpdateAfterId(lastUpdateInfo.getMixUpdateAfterId());
                updateLogInfo.setMixUpdateAfterJson(lastUpdateInfo.getMixUpdateAfterJson());
            }
            /**如果没有说明任务单还未绑定配合比**/
        }

        /**这里获取最后一次任务单扩展信息修改记录*/
        RwdextraExtendUpdateLog rwdextraExtendUpdateLog = rwdextraExtendUpdateLogMapper.selectByLastUpdateInfo(fRwdh);
        if (rwdextraExtendUpdateLog != null) {
            updateLogInfo.setRwdextraExtendAfterId(rwdextraExtendUpdateLog.getId());
            updateLogInfo.setRwdextraExtendAfterJson(rwdextraExtendUpdateLog.getAfterJson());
        } else {
            updateLogInfo.setRwdextraExtendAfterId(null);
            updateLogInfo.setRwdextraExtendAfterJson(new JSONObject());
        }

        /**如果走到这里了 任务单最后没有修改记录的扩展信息 为了第一次的数据做准备 这里需要查询数据 修改前和修改后都要一致 不然之后的流转会有问题*/
        if (updateLogInfo.getRwdextraExtendBeforeId() == null) {
            updateLogInfo.setRwdextraExtendBeforeId(rwdextraExtend.getId());
            updateLogInfo.setRwdextraExtendBeforeJson(JsonUtils.beanToObject(rwdextraExtend));
        }
        if (updateLogInfo.getRwdextraExtendAfterId() == null) {
            updateLogInfo.setRwdextraExtendAfterId(rwdextraExtend.getId());
            updateLogInfo.setRwdextraExtendAfterJson(JsonUtils.beanToObject(rwdextraExtend));
        }

        if (StringUtils.isNotBlank(fPhbNo)) {
            MixProportion mixProportion = mixProportionMapper.selectByPhbNo(fPhbNo);
            if (updateLogInfo.getMixUpdateBeforeId() == null) {
                updateLogInfo.setMixUpdateBeforeId(mixProportion.getId());
                updateLogInfo.setMixUpdateBeforeJson(JsonUtils.beanToObject(mixProportion));
            }
            if (updateLogInfo.getMixUpdateAfterId() == null) {
                updateLogInfo.setMixUpdateAfterId(mixProportion.getId());
                updateLogInfo.setMixUpdateAfterJson(JsonUtils.beanToObject(mixProportion));
            }
        }
        rwdextraUpdateLogMapper.insertSelective(updateLogInfo);
    }

    @Override
    public void delete(Long id) {
        rwdextraUpdateLogMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PrintRwdextraExperimentInfo selectExperimentByFrwdh(Integer updateLogId) {
        RwdextraUpdateLog updateLogInfo = rwdextraUpdateLogMapper.loadById(Long.valueOf(updateLogId));
        assertTrue(updateLogInfo == null, "增补资料记录不存在");
        RwdextraExtend rwdextraExtend = JsonUtils.getObject(updateLogInfo.getRwdextraExtendAfterJson(), RwdextraExtend.class);
        if (rwdextraExtend != null) {
            RwdextraPrintInfo rwdextraPrintInfo = JsonUtils.getObject(rwdextraExtend.getPrintJson(), RwdextraPrintInfo.class);
            if (rwdextraPrintInfo != null) {
                PrintRwdextraExperimentInfo printRwdextraExperimentInfo = new PrintRwdextraExperimentInfo();
                List<Long> kyExperimentIdList = new ArrayList<>();
                if (rwdextraPrintInfo.getKyInfoList() != null && !rwdextraPrintInfo.getKyInfoList().isEmpty()) {
                    for (RwdextraPrintInfo.Kytz kytz : rwdextraPrintInfo.getKyInfoList()) {
                        if (StringUtils.isBlank(kytz.getSytzbh())) {
                            continue;
                        }
                        kyExperimentIdList.add(Long.valueOf(kytz.getSytzbh()));
                    }
                }

                printRwdextraExperimentInfo.setKyInfoList(rwdextraService.getPrintExperimentInfoVo(kyExperimentIdList));
                printRwdextraExperimentInfo.setKsInfoList(rwdextraService.getPrintExperimentInfoVo(rwdextraPrintInfo.getKsExperimentId()));
                printRwdextraExperimentInfo.setKzInfoList(rwdextraService.getPrintExperimentInfoVo(rwdextraPrintInfo.getKzExperimentId()));
                printRwdextraExperimentInfo.setKllzInfoList(rwdextraService.getPrintExperimentInfoVo(rwdextraPrintInfo.getKllExperimentId()));


                /**这里获取所有原材料的  之后在优化先完成功能*/
                MixProportion mixProportion = rwdextraPrintInfo.getMixProportionInfo();
                if (mixProportion != null && mixProportion.getProportionMaterial() != null) {
                    MixProportionReport mixProportionReport = JsonUtils.getObject(mixProportion.getProportionMaterial(), MixProportionReport.class);
                    if (mixProportionReport == null) {
                        return printRwdextraExperimentInfo;
                    }
                    if (mixProportionReport.getSn() != null) {
                        printRwdextraExperimentInfo.setSnInfoList(rwdextraService.getPrintExperimentInfoVo(mixProportionReport.getSn().getPktzid()));
                    }
                    if (mixProportionReport.getXgl() != null) {
                        printRwdextraExperimentInfo.setXglInfoList(rwdextraService.getPrintExperimentInfoVo(mixProportionReport.getXgl().getPktzid()));
                    }
                    if (mixProportionReport.getCgl() != null) {
                        printRwdextraExperimentInfo.setCglInfoList(rwdextraService.getPrintExperimentInfoVo(mixProportionReport.getCgl().getPktzid()));
                    }
                    if (mixProportionReport.getFmh() != null) {
                        printRwdextraExperimentInfo.setFmhInfoList(rwdextraService.getPrintExperimentInfoVo(mixProportionReport.getFmh().getPktzid()));
                    }
                    if (mixProportionReport.getKzf() != null) {
                        printRwdextraExperimentInfo.setKzfInfoList(rwdextraService.getPrintExperimentInfoVo(mixProportionReport.getKzf().getPktzid()));
                    }
                    List<Long> wjjExperimentIdList = new ArrayList<>();
                    if (mixProportionReport.getWjj1() != null && StringUtils.isNotBlank(mixProportionReport.getWjj1().getPktzid())) {
                        wjjExperimentIdList.add(Long.valueOf(mixProportionReport.getWjj1().getPktzid()));
                    }
                    if (mixProportionReport.getWjj2() != null && StringUtils.isNotBlank(mixProportionReport.getWjj2().getPktzid())) {
                        wjjExperimentIdList.add(Long.valueOf(mixProportionReport.getWjj2().getPktzid()));
                    }
                    printRwdextraExperimentInfo.setWjjInfoList(rwdextraService.getPrintExperimentInfoVo(wjjExperimentIdList));
                }
                return printRwdextraExperimentInfo;
            }
        }
        return new PrintRwdextraExperimentInfo();
    }

    @Override
    public RwdextraExtend loadRwdextraById(Long updateLogId) {
        RwdextraUpdateLog rwdextraUpdateLog = rwdextraUpdateLogMapper.loadById(updateLogId);
        RwdextraExtend rwdextraExtend = JsonUtils.getObject(rwdextraUpdateLog.getRwdextraExtendAfterJson(), RwdextraExtend.class);
        assertTrue(rwdextraExtend == null, "ERP任务单扩展信息不存在！");
        Rwdextra rwdextra = rwdextraService.loadByFrwdh(rwdextraUpdateLog.getFrwdh());
        printService.setRwdextraValue(rwdextraExtend, rwdextra);
        RwdextraPrintInfo rwdextraPrintInfo = JsonUtils.getObject(rwdextraExtend.getPrintJson(), RwdextraPrintInfo.class);
        /** 抗渗等级 **/
        if (StringUtils.isNotBlank(rwdextraPrintInfo.getKsdj())) {
            rwdextra.getRwdextraInfo().setKsdj(rwdextraPrintInfo.getKsdj());
        }
        /** 计划日期 **/
        if (StringUtils.isNotBlank(rwdextraPrintInfo.getCustomer().getPlantimeStart())) {
            rwdextra.setPlantime(DateHelper.parseDateTime(DateHelper.getDefaultDateTimeFormat(), DateHelper.getDefaultLocal(), rwdextraPrintInfo.getCustomer().getPlantimeStart()));
        }
        /** 开盘鉴定编号 **/
        if (StringUtils.isNotBlank(rwdextraPrintInfo.getKpjdbh())) {
            rwdextraExtend.setOpenAppraisalNo(rwdextraPrintInfo.getKpjdbh());
        }
        /** 出厂证明签发日期 **/
        if (StringUtils.isNotBlank(rwdextraPrintInfo.getCczmqfrq())) {
            rwdextraExtend.getRwdextraPrintInfo().setCczmqfrq(rwdextraPrintInfo.getCczmqfrq());
        }
        RwdextraPrintInfo.Customer customer = rwdextraPrintInfo.getCustomer();
        /** 完成方量 **/
        if (StringUtils.isNotBlank(customer.getFhquantity())) {
            rwdextra.setFhquantity(Float.valueOf(customer.getFhquantity()));
            rwdextraExtend.setFhquantity(customer.getFhquantity());
        }
        rwdextraExtend.setRwdextra(rwdextra);
        return rwdextraExtend;
    }

    @Override
    public RwdextraExtend generateReport(RwdextraExtend entity) {
        return null;
    }

    @Override
    public List<RwdextraExtend> updateRwdextraUpdateLog(RwdextraExtend entity) {
        return null;
    }

    @Override
    public void updateBatchPrintDetailRwdextra(RwdextraUpdateLogDto rwdextraUpdateLogDto) {
        for (Long updateLogId : rwdextraUpdateLogDto.getUpdateLogIdList()) {
            RwdextraUpdateLog rwdextraUpdateLog = rwdextraUpdateLogMapper.loadById(updateLogId);
            RwdextraExtend rwdextraExtend = JsonUtils.getObject(rwdextraUpdateLog.getRwdextraExtendAfterJson(), RwdextraExtend.class);
            rwdextraExtend.setProjectName(rwdextraUpdateLogDto.getProjectName());
            rwdextraExtend.setContractName(rwdextraUpdateLogDto.getCustomerName());
            RwdextraPrintInfo rwdextraPrintInfo = JsonUtils.getObject(rwdextraExtend.getPrintJson(), RwdextraPrintInfo.class);
            RwdextraPrintInfo.Customer customer = rwdextraPrintInfo.getCustomer() == null ? new RwdextraPrintInfo.Customer() : rwdextraPrintInfo.getCustomer();
            customer.setCustomerName(rwdextraUpdateLogDto.getCustomerName());
            customer.setProjectName(rwdextraUpdateLogDto.getProjectName());
            rwdextraPrintInfo.setCustomer(customer);
            rwdextraExtend.setPrintJson(JsonUtils.beanToObject(rwdextraPrintInfo));
            rwdextraUpdateLog.setRwdextraExtendAfterJson(JsonUtils.beanToObject(rwdextraExtend));
            rwdextraUpdateLogMapper.updateByPrimaryKeySelective(rwdextraUpdateLog);
        }
    }
}
